layui.config({
    base : "js/information/"
}).use(['form','layer','jquery','laypage','laydate'],function(){
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        laydate = layui.laydate,
        $ = layui.jquery;

    var pageSize = 3;
    var currPage = 0;

    initList();

    function initList(){
        var title = $("#search_input").val().replace(/(^\s*)|(\s*$)/g,"");
        var navType = $("#navType").val();
        var startTime = $("#startTime").val().replace(/(^\s*)|(\s*$)/g,"");
        var endTime = $("#endTime").val().replace(/(^\s*)|(\s*$)/g,"");

        if(startTime) startTime = startTime + " 00:00:00";
        if(endTime) endTime = endTime + " 23:59:59";

        // 页面初始化
        var data = {page:currPage,pageSize:pageSize,title:title,startTime:startTime,endTime:endTime,navType:navType};
        $.ajax({
            type: 'POST',
            dataType : "text",
            url: "/information/getInformationList",
            data: data,
            success: function(data){
                var data = data.replace(/id\":(\d+),/g,"id\":\"$1\",");
                data = $.parseJSON(data);
                var html = template('informationList', data);
                document.getElementById('informationListTb').innerHTML = html;
                if(currPage >= 0) initPage(data["total"]);
            },
            error: function(){
                console.log("请求失败");
            }
        });
    }

    //查询
    $("#searchBtn").click(function(e){

        e.preventDefault();
        e.stopPropagation();

        var title = $("#search_input").val().replace(/(^\s*)|(\s*$)/g,"");
        var navType = $("#navType").val();
        var startTime = $("#startTime").val().replace(/(^\s*)|(\s*$)/g,"");
        var endTime = $("#endTime").val().replace(/(^\s*)|(\s*$)/g,"");

        if(startTime) startTime = startTime + " 00:00:00";
        if(endTime) endTime = endTime + " 23:59:59";

        //if(title != '' && typeof title != undefined){
            var index = layer.msg('查询中,请稍候',{icon: 16,time:false,shade:0.8});

            currPage = 0;
            var data = {page:currPage,pageSize:pageSize,title:title,startTime:startTime,endTime:endTime,navType:navType};
            $.ajax({
                cache: false,
                dataType : "text",
                async: false,
                type: 'POST',
                url: "/information/getInformationList",
                data: data,
                success: function(res){
                    var res = res.replace(/id\":(\d+),/g,"id\":\"$1\",");
                    res = $.parseJSON(res);
                    var html = template('informationList', res);
                    document.getElementById('informationListTb').innerHTML = html;
                    if(currPage >= 0) initPage(res["total"]);
                    layer.close(index);
                },
                error: function(){
                    layui.layer.tips('查询失败,请重试', '.layui-layer-setwin .layui-layer-close', {tips: 3});
                    layer.close(index);
                }
            });

            // setTimeout(function(){
            //     layer.close(index);
            // },2000);
        //}else{
            //layer.msg("请输入标题");
        //}
    });

    // 资讯编辑
    //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
    $(window).one("resize",function(){
        $("#informationListTb").on("click",".editBtn",function () {
            var infoId = $(this).attr("infoId");
            console.log("infoId>>>>>>>>>>>>>>>>>>>>"+infoId);
            var index = layui.layer.open({
                title : "资讯编辑",
                type : 2,
                //content : "../../page/information/informationEdit.html?id="+infoId,
                content : "/information/editInformation?id="+infoId,
                success : function(layero, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回资讯列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },300);
                }
            })
            layui.layer.full(index);
        })
    }).resize();


    // 资讯删除
    $(window).one("resize",function(){
        $("#informationListTb").on("click",".delBtn",function () {
            var infoId = $(this).attr("infoId");
            console.log("infoId>>>>>>>>>>>>>>>>>>>>"+infoId);
            $.ajax({
                type: 'POST',
                url: "/information/deleteInformationById?id="+infoId,
                success : function(data){
                    if(data["result"] == "success"){
                        layer.msg('删除成功');
                        initList();
                    }else{
                        layer.msg('系统异常或资源被其他配置绑定，请检查后下架删除或联系管理员');
                    }
                },
                error : function(){
                    layer.msg('删除失败');
                }
                })
        })
    }).resize();

    //添加资讯
    //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
    $(window).one("resize",function(){
        $(".informationAdd_btn").click(function(){
            var index = layui.layer.open({
                title : "添加资讯",
                type : 2,
                content : "../../page/information/informationAdd.html",
                success : function(layer, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回剧集列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            })
            layui.layer.full(index);
        })
    }).resize();




    //批量删除
    $(".batchDel").click(function(){
        var $checkbox = $('.informations_list tbody input[type="checkbox"][name="checked"]');
        var $checked = $('.informations_list tbody input[type="checkbox"][name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                setTimeout(function(){
                    // //删除数据
                    // for(var j=0;j<$checked.length;j++){
                    // 	for(var i=0;i<newsData.length;i++){
                    // 	if(newsData[i].newsId == $checked.eq(j).parents("tr").find(".news_del").attr("data-id")){
                    // 		newsData.splice(i,1);
                    // 		newsList(newsData);
                    // 	}
                    // }
                    // }
                    // $('.news_list thead input[type="checkbox"]').prop("checked",false);
                    // form.render();

                    alert("批量删除");
                    layer.close(index);
                    layer.msg("删除成功");
                },2000);
            })
        }else{
            layer.msg("请选择需要删除的文章");
        }
    })

    //全选
    form.on('checkbox(allChoose)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
        }
        form.render('checkbox');
    })

    //是否展示
    form.on('switch(isShow)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
            layer.close(index);
            layer.msg("展示状态修改成功！");
        },2000);
    })

    //操作
    $("body").on("click","#informationEdit",function(){  //编辑
        layer.alert('您点击了文章编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。',{icon:6, title:'文章编辑'});
    })

    $("body").on("click","#informationCollect",function(){  //收藏.
        if($(this).text().indexOf("已收藏") > 0){
            layer.msg("取消收藏成功！");
            $(this).html("<i class='layui-icon'>&#xe600;</i> 收藏");
        }else{
            layer.msg("收藏成功！");
            $(this).html("<i class='iconfont icon-star'></i> 已收藏");
        }
    })

    $("body").on("click","#informationDel",function(){  //删除
        var _this = $(this);
        layer.confirm('确定删除此信息?',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();

            // for(var i=0;i<newsData.length;i++){
            // 	if(newsData[i].newsId == _this.attr("data-id")){
            // 		newsData.splice(i,1);
            // 		newsList(newsData);
            // 	}
            // }
            layer.close(index);
        });
    })

    // 分页
    function initPage(total){
        console.log(">>>>>>>>>>>initPage<<<<<<<<<<<");

        laypage({
            cont : "pagination",
            pages : Math.ceil(total/pageSize),
            curr : currPage + 1,
            skip : true,
            jump : function(obj,first){
                // $(".news_content").html(renderDate(newsData,obj.curr));
                // $('.news_list thead input[type="checkbox"]').prop("checked",false);
                // form.render();

                currPage = obj.curr - 1;
                console.log("*********11111111111111");
                if(!first){
                    //window.location.href="/getAllInformationList?page="+obj.curr;
                    initList();
                    $('#informations_list thead input[type="checkbox"]').prop("checked",false);
                    form.render();
                }else{
                    $('#informations_list thead input[type="checkbox"]').prop("checked",false);
                    form.render();
                }
            }
        })
    }


    // 进入资讯详情页:
    //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
    $(window).one("resize",function(){
        $("#informationListTb").on("click",".title",function () {
            var infoId = $(this).attr("id");
            console.log("infoId>>>>>>>>>>>>>>>>>>>>"+infoId);
            // window.top.location.href = '/api/detail/information/'+infoId;
            window.open('/api/detail/information/'+infoId);
        })
    }).resize();
})
